package own.stu.jobgib.playown.grpc.server;

import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import own.stu.jobgib.playown.grpc.proto.GreeterGrpc;
import own.stu.jobgib.playown.grpc.proto.HelloReply;
import own.stu.jobgib.playown.grpc.proto.HelloRequest;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class HelloWorldServer {

    private Server server;

    private void start() throws IOException {
        server = ServerBuilder.forPort(Args.port)
                .addService(new GreeterImpl())
                .build()
                .start();

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                stop();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }));
    }

    private void stop() throws InterruptedException {
        if(server != null){
            server.shutdown().awaitTermination(20, TimeUnit.SECONDS);
        }
    }

    /**
     * Await termination on the main thread since the grpc library uses daemon threads.
     */
    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        final HelloWorldServer server = new HelloWorldServer();
        server.start();
        server.blockUntilShutdown();
    }

    static class GreeterImpl extends GreeterGrpc.GreeterImplBase{

        @Override
        public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
            HelloReply reply = HelloReply.newBuilder()
                    .setMessage("hello " + request.getName())
                    .build();
            System.out.println(" ======= ");
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    private static class Args{
        public static int port = 8999;
    }
}
